/**
 * 菜单, 动态路由转化
 * Created by Janus on 18/11/19.
 */

import router from './router'
import {
  dynamicRouters
} from './router'
import {
  menusTreeToList,
  menusListToMap
} from '@/utils/menusUtil'
// import {
//   setTheme
// } from '@/utils/theme'
import store from './store'
import Layout from '@/views/layout/layout'
import { setOem } from './utils/oem'

setOem()

import {
  Message
} from 'element-ui'
import {
  getToken
} from '@/utils/auth' // 验权
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式

const whiteList = ['/login'] // 不重定向白名单

const menusToRouter = (menus) => {
  const routes = []
  const menusMap = menusListToMap(menusTreeToList(menus))
  for (let i = 0; i < dynamicRouters.length; i++) {
    const route = dynamicRouters[i]
    if (menusMap[route.name]) {
      route.meta = menusMap[route.name]
      route.meta.keepAlive = route.keepAlive || false
      routes.push(route)
    }
  }
  return routes
}

router.beforeEach((to, from, next) => {
  NProgress.start()

  // step 1: 白名单
  if (whiteList.indexOf(to.path) !== -1) {
    next()
    return
  }

  // step 2: 检查token
  if (!getToken()) {
    localStorage.setItem('routerQuery', JSON.stringify(to.query))
    // next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    next(`/login`) // 否则全部重定向到登录页
    NProgress.done()
    return
  }

  // step 3: 检查用户信息
  if (store.getters.userLoaded) {
    // 更新当前路由状态
    store.dispatch('RefreshCurMenu', to)
    if (to.name && to.path === '/') {
      next('/404')
    } else {
      next()
    }
    return
  }

  store.dispatch('GetInfo').then(res => {
    const { business } = res.data
    // console.log('userInfo', res)
    const menus = res.data.menus
    // 加载用户主题
    // setTheme().then(() => {

    // 更新网页标题
    if (res.data.business.oemConfig && res.data.business.oemConfig.bisWebTitle) {
      document.title = res.data.business.oemConfig.bisWebTitle
    }

    // 刷新用户菜单
    store.dispatch('ReloadMenus', menus)

    // if (business.syncTmpMerchantId) {
    //   // 流量预警信息
    //   store.dispatch('mercFlowAlert', {
    //     merchantId: business.syncTmpMerchantId
    //   })
    // }

    // 挂载异步路由
    const childRouters = menusToRouter(menus)
    if (childRouters.length) {
      const first = {
        path: '/',
        component: Layout,
        redirect: childRouters[0].path,
        name: 'home',
        hidden: true
      }
      const asyncRouters = [
        first,
        {
          path: '/',
          component: Layout,
          name: 'layout',
          hidden: false,
          children: childRouters
        },
        {
          path: '*',
          name: 'all',
          redirect: '/404',
          hidden: true
        }
      ]
      // console.log(asyncRouters)
      router.addRoutes(asyncRouters)
    }
    if (!to.name) {
      const curRouter = router.match(to.fullPath)
      // if (to.path === '/' && store.state.menus.homePageMenu) {
      //   next({ name: store.state.menus.homePageMenu.code })
      // } else
      if (curRouter.name && curRouter.name !== '404') {
        next({
          ...curRouter
        })
      } else {
        next('/404')
      }
      NProgress.done()
    } else {
      next()
    }
    // });
  }).catch((err) => {
    store.dispatch('FedLogOut').then(() => {
      Message.error(err || 'Verification failed, please login again')
      next({
        path: '/'
      })
    })
  })
})

router.afterEach(() => {
  // 挂载异步路由
  NProgress.done()
})
